package com.ocom.company.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ocom.common.constant.MapKey;
import com.ocom.common.constant.UserConstants;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.master.EntityCompanyRole;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.StringUtils;
import com.ocom.company.dao.IDaoMngUserInfo;
import com.ocom.company.feign.HumanClient;
import com.ocom.company.service.CompanyRoleService;
import com.ocom.company.service.MngUserInfoService;
import com.ocom.company.vo.GetCompanyListByPhoneVo;
import com.ocom.common.vo.company.GetMngUserInfoVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class MngUserInfoServiceImpl extends ServiceImpl<IDaoMngUserInfo, EntityMngUserInfo> implements MngUserInfoService {

    //注入MngUserInfo 持久层
    @Autowired
    private IDaoMngUserInfo daoMngUserInfo;

    @Autowired
    private CompanyRoleService companyRoleService;

    @Autowired
    private HumanClient humanClientService;

    /**获取管理员用户信息*/
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityMngUserInfo GetMngUserInfo(Long comId, GetMngUserInfoVo getMngUserInfoVo) {

        QueryWrapper<EntityMngUserInfo> mngUserInfoQueryWrapper = Wrappers.query();
        if (StringUtils.isNotNull(getMngUserInfoVo.getId())){
            mngUserInfoQueryWrapper.eq("id",getMngUserInfoVo.getId());
        }
        if (StringUtils.isNotNull(getMngUserInfoVo.getComId())){
            mngUserInfoQueryWrapper.eq("com_id",getMngUserInfoVo.getComId());
        }
        if (StringUtils.isNotEmpty(getMngUserInfoVo.getUserName())){
            mngUserInfoQueryWrapper.eq("user_name",getMngUserInfoVo.getUserName());
        }
        if (StringUtils.isNotNull(getMngUserInfoVo.getRole())){
            mngUserInfoQueryWrapper.eq("role",getMngUserInfoVo.getRole());
        }
        if (StringUtils.isNotNull(getMngUserInfoVo.getRegionId())){
            mngUserInfoQueryWrapper.eq("region_id",getMngUserInfoVo.getRegionId());
        }
        mngUserInfoQueryWrapper.last("limit 1");

        return daoMngUserInfo.selectOne(mngUserInfoQueryWrapper);
    }
    //再根据list1.p_id查询表 mng_user_info as list3（list1.p_id=list3.id）
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityMngUserInfo GetMngUserInfo(Long pId) {
        QueryWrapper<EntityMngUserInfo> query = Wrappers.query();
        query.eq("id",pId);
        return daoMngUserInfo.selectOne(query);
    }

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster= MasterSlaveEnum.SLAVE)
    @Override
    public EntityMngUserInfo GetMngUserInfoByName(String userName) {
        QueryWrapper<EntityMngUserInfo> mngUserInfoQueryWrapper = Wrappers.query();
        mngUserInfoQueryWrapper.eq("user_name",userName);
        return this.getOne(mngUserInfoQueryWrapper);
    }

    /**
     * 获取单位下用户数
     * */
    @Override
    public Map<String,Object> GetCompanyPersonNum(Long comId, String deptId, Long status) {

        QueryWrapper<EntityMngUserInfo> wrapper = Wrappers.query();
        if (StringUtils.isNotNull(comId)){
            wrapper.eq("com_id",comId);
        }
        if (StringUtils.isNotNull(deptId)){
            wrapper.eq("dept_id",deptId);
        }
        if (StringUtils.isNotNull(status)){
            wrapper.eq("status",status);
        }
        Long selectCount = Long.valueOf(daoMngUserInfo.selectCount(wrapper));
        MapKey mapKey = new MapKey();
        HashMap<String, Object> map = new HashMap<>();
        map.put(mapKey.getKey_comId(),comId);
        map.put(mapKey.getKey_num(),selectCount);
        return map;
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public String checkUserNameUnique(String userName) {
        QueryWrapper<EntityMngUserInfo> query = Wrappers.query();
        query.eq("user_name",userName).last("limit 1");
        //校验
        EntityMngUserInfo entityMngUserInfo = daoMngUserInfo.selectOne(query);
        //存在
        if (StringUtils.isNotNull(entityMngUserInfo) && userName.equals(entityMngUserInfo.getUserName()))   {
            return UserConstants.NOT_UNIQUE;
        }
        //不存在
        return UserConstants.UNIQUE;
    }

    /**在mng_user_info新增用户*/
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public Map<String, Object> AddCompanyAdminInfo(EntityMngUserInfo entityMngUserInfo) {
        //生成8位数随机盐
        String rundom = getRundom();
        entityMngUserInfo.setSalt(rundom);
        //生成随机盐和密码加密后的字符串
        entityMngUserInfo.setPassword(encryptPassword(entityMngUserInfo.getPassword()+rundom));

        daoMngUserInfo.insert(entityMngUserInfo);
        HashMap<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(), entityMngUserInfo.getComId());
        map.put(mapKey.getKey_userName(), entityMngUserInfo.getUserName());
        map.put(mapKey.getKey_pId(), entityMngUserInfo.getId());
        return map;
    }

    /**
     * 更新管理员信息
     * */
    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public Map<String, Object> UpdateMngUserInfo(EntityMngUserInfo entityMngUserInfo) {
        QueryWrapper<EntityMngUserInfo> query = Wrappers.query();
        if (StringUtils.isNotEmpty(entityMngUserInfo.getUserName())){
            query.eq("user_name",entityMngUserInfo.getUserName());
        }
        if (StringUtils.isNotEmpty(entityMngUserInfo.getPassword())){
            //生成随机盐和密码加密后的字符串
            //生成8位数随机盐
            String rundom = getRundom();
            if (StringUtils.isEmpty(entityMngUserInfo.getSalt())){
                entityMngUserInfo.setSalt(rundom);
            }
            entityMngUserInfo.setPassword(encryptPassword(entityMngUserInfo.getPassword()+rundom));
        }
        daoMngUserInfo.update(entityMngUserInfo,query);
        HashMap<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(), entityMngUserInfo.getComId());
        map.put(mapKey.getKey_userName(), entityMngUserInfo.getUserName());
        map.put(mapKey.getKey_pId(), entityMngUserInfo.getId());
        return map;
    }
    /**
     * 根据手机号获取管理员用户列表（/getMngUserInfoByPhone）
     *
     * @return*/
    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityMngUserInfo GetMngUserInfoByPhone(Long comId,String phone) {
        QueryWrapper<EntityMngUserInfo> query = Wrappers.query();
        query.eq("com_id",comId);
        query.eq("phone",phone);
        return daoMngUserInfo.selectOne(query);
    }

    /**
     * 2.21.手机号获取可管理单位（getCompanyListByPhone）
     * */
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<GetCompanyListByPhoneVo> GetCompanyListByPhone(String phone) {

        return daoMngUserInfo.GetCompanyListByPhone(phone);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityMngUserInfo> getMngUserList(List<Long> ids) {
        return this.listByIds(ids);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityMngUserInfo getUserByNameAndRole(String account, String role) {

        return daoMngUserInfo.getUserByNameAndRole(account,role);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityMngUserInfo> getUserByRole(Long companyId, Long role, Long deptId) {
        Integer parentRole = 0;
        Set<Long> roleList = new HashSet<>();
        roleList.add(role);

        Set<Long> deptIdList = new HashSet<>();

        if(role > 10000L){
            EntityCompanyRole entityCompanyRole = this.companyRoleService.getComRole(companyId,role);
            parentRole = entityCompanyRole.getParentRole();
        }

        if(parentRole.equals(23) || role.equals(23L)){
            deptIdList.add(deptId);
            this.companyRoleService.getByParentRole(23).forEach(entityCompanyRole->{
                if(role.equals(entityCompanyRole.getRoleId())){

                    roleList.add(entityCompanyRole.getRoleId());
                }

            });

            Result<List<EntityDeptInfo>> deptList = humanClientService.getDeptList(companyId,deptId,1);

            ENDDEPT:
            for (int i =1 ;i<=5;i++){
                for (EntityDeptInfo entityDeptInfo:deptList.getData()){
                    if(entityDeptInfo.getDeptId().equals(deptId)){
                        if(deptId== 0L) break ENDDEPT;
                        deptIdList.add(entityDeptInfo.getParentDeptId());
                        break ;
                    }
                }
            }
        }

        GetMngUserInfoVo getMngUserInfoVo = new GetMngUserInfoVo();
        getMngUserInfoVo.setRole(role);


        return this.getMngUserList(companyId, Lists.newArrayList(roleList),Lists.newArrayList(deptIdList));
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityMngUserInfo> getMngUserList(Long comId,  List<Long> roleIds,List<Long> deptIds) {
        return this.list(Wrappers.lambdaQuery(EntityMngUserInfo.class)
                .eq(EntityMngUserInfo::getComId,comId)
                .in(EntityMngUserInfo::getRole,roleIds)
                .in(ObjectUtil.isNotEmpty(deptIds),EntityMngUserInfo::getDeptId,deptIds)
        );
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        return passwordEncoder.encode(password);
    }


    private static String getRundom(){
//         48-57 65-90 97-122
        StringBuilder id=new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            char str = 0;
            int j=random.nextInt(3) % 4;
            switch (j) {
                case 0:
                    //随机生成数字
                    str = (char) (random.nextInt(57) % (57 - 48 + 1) + 48);
                    break;
                case 1:
                    //随机生成大写字母
                    str = (char) (random.nextInt(90) % (90 - 65 + 1) + 65);
                    break;
                case 2:
                    //随机生成小写字母
                    str = (char) (random.nextInt(122) % (122 - 97 + 1) + 97);
                    break;
            }
            id.append(str);
        }
        return id.toString();
    }


}
